package com.innovation.sys.common.shiro.filter;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.innovation.sys.pojo.SSysAccount;
import com.innovation.sys.pojo.SSysLog;
import com.innovation.sys.service.LogAdminService;

@Service
public class SystemLogoutFilter extends LogoutFilter {

	private static Logger logger = LoggerFactory.getLogger(SystemLogoutFilter.class);

	@Resource
	private LogAdminService logAdminService;

	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		Subject subject = getSubject(request, response);
		String redirectUrl = getRedirectUrl(request, response, subject);
		try {
			SSysAccount account = (SSysAccount) SecurityUtils.getSubject().getSession().getAttribute("user");
			// 保存日志信息
			SSysLog sSysLog = new SSysLog();
			sSysLog.setCreateTime(new Date());
			sSysLog.setLogDesc("登出操作");
			sSysLog.setLogUser(account.getUserName());
			logAdminService.addLog(sSysLog);
			subject.logout();
		} catch (SessionException ise) {
			logger.info("error:{}", ise);
		}
		issueRedirect(request, response, redirectUrl);
		return false;
	}

}
